/* Copyright (c) 2021, National University of Defense Technology. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "bsr_common.h"
#include "parbsr_jacobi_preconditioner.h"

namespace YHAMG
{

ParBSR_Jacobi_Preconditioner::ParBSR_Jacobi_Preconditioner()
	: size(0),
	block_size(0),
	D_LU(0)
{
}

ParBSR_Jacobi_Preconditioner::~ParBSR_Jacobi_Preconditioner()
{
	if (D_LU) delete[] D_LU;
}

void ParBSR_Jacobi_Preconditioner::Free()
{
	if (D_LU) delete[] D_LU;
	size = 0;
	block_size = 0;
	D_LU = 0;
}

void ParBSR_Jacobi_Preconditioner::Setup(const ParBSR_Matrix& A, int REUSE)
{
	if (REUSE == 0)
	{
		comm = A.comm;
		if (D_LU) delete D_LU;
		size = A.LocLoc.size[0];
		block_size = A.LocLoc.block_size;
		D_LU = new double[size * block_size * block_size];
	}

	int block_nnz = block_size * block_size;
	int* Ap = A.LocLoc.rowptr;
	int* Ai = A.LocLoc.colind;
	double* Av = A.LocLoc.values;

#ifdef USE_OPENMP
#pragma omp parallel for schedule(guided)
#endif
	for (int i = 0; i < size; ++i)
	{
		for (int j = Ap[i]; j < Ap[i + 1]; ++j)
		{
			if (Ai[j] == i)
			{
				BSRBlockCopy(block_size, Av + j * block_nnz, D_LU + i * block_nnz);
				BSRBlockLUFactorize(block_size, D_LU + i * block_nnz);
				break;
			}
		}
	}
}

int ParBSR_Jacobi_Preconditioner::InSize() const
{
	return size * block_size;
}

int ParBSR_Jacobi_Preconditioner::OutSize() const
{
	return size * block_size;
}

void ParBSR_Jacobi_Preconditioner::Apply(const Par_Vector& b, const Par_Vector& x) const
{
	int block_nnz = block_size * block_size;

	if (b.Loc.values != x.Loc.values)
		x.Loc.Copy(b.Loc);

	double* xv = x.Loc.values;

#ifdef USE_OPENMP
#pragma omp parallel for
#endif
	for (int i = 0; i < size; ++i)
		BSRBlockLUVecSolve(block_size, D_LU + i * block_nnz, xv + i * block_size);
}

}